const elId = `tui_${Math.ceil(Math.random() * 10e5).toString(36)}`
const elId_box = `tui_${Math.ceil(Math.random() * 10e5).toString(36)}`
Component({
  properties: {
    //滚动容器宽度 rpx ，0 则使用屏幕宽度
    width: {
      type: String,
      optionalTypes: [Number],
      value: 0
    },
    //滚动容器高度 rpx
    height: {
      type: String,
      optionalTypes: [Number],
      value: 400,
      observer(val) {
        this.setData({
          scrollHeight: this.rpx2px(val)
        })
      }
    },
    background: {
      type: String,
      value: 'transparent'
    },
    radius: {
      type: String,
      optionalTypes: [Number],
      value: 0
    },
    padding: {
      type: String,
      value: '0'
    },
    //每秒滚动速度（距离） 默认 20px/s
    speed: {
      type: String,
      optionalTypes: [Number],
      value: 20
    },
    //backwards: 动画从头开始播；forwards：动画从结束点开始播
    activeMode: {
      type: String,
      value: 'backwards'
    }
  },
  data: {
    elId,
    elId_box,
    webviewHide: false,
    boxHeight: 0,
    contentHeight: 0,
    scrollHeight: 0,
    animationDuration: 'none',
    animationPlayState: 'paused',
    animationDelay: '0s'
  },
  lifetimes: {
    attached: function () {
      this.setData({
        scrollHeight: this.rpx2px(this.data.height)
      })
    },
    ready: function () {
      setTimeout(() => {
        this.initAnimation()
      }, 50)
    }
  },
  methods: {
    rpx2px(value) {
      let sys = wx.getSystemInfoSync()
      return sys.windowWidth / 750 * Number(value)
    },
    initAnimation() {
      let query = [];
      let noticeQuery = new Promise((resolve, reject) => {
        wx.createSelectorQuery()
          .in(this)
          .select(`#${this.data.elId}`)
          .boundingClientRect()
          .exec(ret => {
            this.setData({
              contentHeight: ret[0].height
            })
            resolve()
          })
      })
      if (this.data.activeMode === 'forwards') {
        let boxQuery = new Promise((resolve, reject) => {
          wx.createSelectorQuery()
            .in(this)
            .select(`#${this.data.elId_box}`)
            .boundingClientRect()
            .exec(ret => {
              this.setData({
                boxHeight: ret[0].height
              })
              resolve()
            })
        })
        query.push(boxQuery)
      }
      query.push(noticeQuery)
      const data = {}
      Promise.all(query).then(() => {
        data.animationDuration = `${this.data.contentHeight /(Number(this.data.speed) || 20)}s`
        if (this.data.activeMode === 'forwards') {
          data.animationDelay = `-${this.data.boxHeight / (Number(this.data.speed) || 20)}s`
        }
        this.setData(data)
        setTimeout(() => {
          this.setData({
            animationPlayState: 'running'
          })
        }, 1000)
      })

    }
  }
})